package com.wnhz.work.yz.activity.register;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * ---邀请码
 */
public class Register4Activity extends BaseActivity implements View.OnClickListener {
    private TextView tv_right;
    private EditText et_invite;

    private String phone;
    private String code;
    private String passWord;
    private String invite;

    private String click;

    /**
     * 扫描跳转Activity RequestCode
     */
    public static final int REQUEST_CODE = 111;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 845;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register4);

        initData();
        initView();
    }

    private void initData() {
        phone = getIntent().getStringExtra("phone");
        code = getIntent().getStringExtra("code");
        passWord = getIntent().getStringExtra("passWord");
    }

    private void initView() {
        findViewById(R.id.view_main_middle_title).setVisibility(View.GONE);
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.btn_main_right).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_main_right).setOnClickListener(this);
        tv_right = (TextView) findViewById(R.id.view_main_right_text);
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("跳过");
        tv_right.setTextColor(0xff008c99);

        et_invite = (EditText) findViewById(R.id.et_invite);
        findViewById(R.id.iv_invite).setOnClickListener(this);
        findViewById(R.id.tv_finish).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //跳过
            case R.id.btn_main_right:
                upload1();
                break;

            //扫码
            case R.id.iv_invite:
                scanCode();
                break;

            //完成
            case R.id.tv_finish:
                invite = et_invite.getText().toString();
                if (!"".equals(invite)) {
                    upload();
                } else {
                    MyToast("请输入邀请码");
                }
                break;

            default:
                break;
        }
    }

    public void scanCode() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE);
        } else {
            startActivityForResult(new Intent(this, CaptureActivity.class), REQUEST_CODE);
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startActivityForResult(new Intent(this, CaptureActivity.class), REQUEST_CODE);
            } else {
                MyToast("很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。");
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Log.e(TAG, "onActivityResult:getInviteCode===1 " + result);
//                    String s = "pid/";
                    getInviteCode(result);
//                    if (result.indexOf(s) > 0) {
//                        String pId = result.substring(result.indexOf(s) + s.length(), result.length());
//                        Log.e(TAG, "onActivityResult:getInviteCode===2 " + pId);
//                        getInviteCode(pId);
//                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    MyToast("无效的二维码");
                }
            }
        }
    }


    private void getInviteCode(String pId) {
        Map<String, Object> map = new HashMap<>();
        Log.e(TAG, "onSuccess: getInviteCode===bbbb " + pId);
        map.put("url", pId);
        showDialog();
        XUtil.Post(Url.DECODEURL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: getInviteCode===aaa " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String str = jsonObject.optString("result");
                    String code = jsonObject.optString("info");
                    if ("1".equals(str)) {
                        et_invite.setText(code);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                Log.e(TAG, "onFinished: ");
                closeDialog();
            }
        });
    }

    private void upload1() {
        showDialog();
        invite = et_invite.getText().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("password", passWord);
        map.put("code", code);
        map.put("inviteCode", "");
        XUtil.Post(Url.USER_REGISTE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: inviteCode= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        MyToast(info);
                        Intent intent = new Intent(Register4Activity.this, RegisterSuccessActivity.class);
                        intent.putExtra("phone", phone);
                        startActivity(intent);
                    } else {
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private static final String TAG = "Register4Activity";

    private void upload() {
        showDialog();
        invite = et_invite.getText().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("password", passWord);
        map.put("code", code);
        map.put("inviteCode", invite);
        XUtil.Post(Url.USER_REGISTE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String message = jsonObject.optString("message");
                    if ("1".equals(res)) {
                        MyToast(message);
                        Intent intent = new Intent(Register4Activity.this, RegisterSuccessActivity.class);
                        intent.putExtra("phone", phone);
                        startActivity(intent);
                    } else {
                        MyToast(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }
}
